home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1976 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: Rezonet.net!news
  2. From: ray@ultimate-tech.com (Ray Dunn)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: swap high and low 16 bits?
  5. Date: 18 Jan 1996 04:23:33 GMT
  6. Organization: Ultimate Technographics Inc.
  7. Message-ID: <4dki05$104c@ns.RezoNet.NET>
  8. References: <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
  9. NNTP-Posting-Host: 204.19.230.7
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-Newsreader: WinVN 0.99.7
  13.  
  14. In referenced article, Bill Simpson says...
  15. >
  16. >I wanted to obtain a "random" starting number each time a program
  17. >is run.  The obvious choice is time(NULL).  The problem with it is 
  18. >that if the program runs and terminates fairly quickly, the number 
  19. >returned by time(NULL) is quite similar each run, differing only by 
  20. >the lowest bits.
  21.  
  22. If you use the number you get from time as the seed of the random 
  23. number generator i.e. srand((unsigned int)time(NULL)); then use rand() 
  24. to get a random number in the range 0 to RAND_MAX (which is usually the 
  25. maximum integer)  This should be exactly what you want. The rand 
  26. functions are defined in stdlib.h;
  27.  
  28. >One solution would be to swap the high 16 bits and the low 16 bits of 
  29. >the 32 bit unsigned long int.  Sorry this is dirty, not ANSI.
  30.  
  31. This would give you a number that was numerically very different each 
  32. time, but the low 16-bits would be the same every run.  Probably not 
  33. what you want, but you can do it easily in arithmetic:
  34.  
  35.   number = (number >> 16) | (number << 16);
  36.  
  37. If you don't currently understand bitwise operations, then try:
  38.  
  39.   number = number / 65536 + (number % 65536) * 65536;
  40.  
  41. [ % is the modulus operator - it produces the remainder, and is 
  42. required to avoid the * 65536 giving integer overflow, which may 
  43. cause a trap on you machine]
  44.  
  45. number must be unsigned for this to have the effect you want.
  46. -- 
  47. Ray Dunn (opinions are my own) | Phone: (514) 938 9050
  48. Montreal                       | Phax : (514) 938 5225
  49. ray@ultimate-tech.com          | Home : (514) 630 3749
  50.  
  51.